package com.example.security.mapper;

import com.example.security.entity.SysPermission;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 系统权限Mapper接口
 * 处理权限相关的数据库操作
 */
@Mapper
public interface SysPermissionMapper {

    @Select("SELECT * FROM sys_permission")
    List<SysPermission> selectAll();

    @Select("SELECT * FROM sys_permission WHERE id = #{id}")
    SysPermission selectById(Long id);

    @Select("SELECT * FROM sys_permission WHERE enname = #{enname}")
    SysPermission selectByEnname(String enname);

    @Select("SELECT COUNT(*) FROM sys_permission WHERE parent_id = #{parentId}")
    int countByParentId(Long parentId);

    @Insert("INSERT INTO sys_permission(parent_id, name, enname, url, type, sort, icon, status, description) " +
            "VALUES(#{parentId}, #{name}, #{enname}, #{url}, #{type}, #{sort}, #{icon}, #{status}, #{description})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(SysPermission permission);

    @Update("UPDATE sys_permission SET parent_id=#{parentId}, name=#{name}, enname=#{enname}, " +
            "url=#{url}, type=#{type}, sort=#{sort}, icon=#{icon}, status=#{status}, " +
            "description=#{description} WHERE id=#{id}")
    void update(SysPermission permission);

    @Delete("DELETE FROM sys_permission WHERE id = #{id}")
    void deleteById(Long id);

    /**
     * 查询用户权限列表
     * 包括角色权限和直接授权的权限
     */
    @Select("SELECT permission_code FROM sys_permission WHERE id IN " +
           "(SELECT permission_id FROM sys_role_permission WHERE role_id IN " +
           "(SELECT role_id FROM sys_user_role WHERE user_id = #{userId}))")
    List<String> selectPermissionsByUserId(Long userId);

    /**
     * 查询角色权限列表
     */
    @Select("SELECT DISTINCT p.enname FROM sys_permission p " +
            "LEFT JOIN sys_role_permission rp ON p.id = rp.permission_id " +
            "WHERE rp.role_id = #{roleId}")
    List<String> selectPermissionsByRoleId(Long roleId);

    /**
     * 查询所有权限列表
     */
//    @Select("SELECT * FROM sys_permission WHERE type = 'permission'")
//    List<SysPermission> selectPermissionList(PermissionQuery query);

    /**
     * 查询菜单权限列表
     */
    @Select("SELECT * FROM sys_permission WHERE type = 'menu'")
    List<SysPermission> selectMenuPermissions();
} 